package com.faxsun.controller.account.validator;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.faxsun.captcha.service.FSCaptchaService;
import com.faxsun.captcha.service.FSDigitalCaptchaServiceImpl;
import com.faxsun.controller.account.FSUpdateMobileForm;
import com.faxsun.profile.core.service.FSCustomerService;

@Component("fsUpdateMobileValidator")
public class UpdateMobileValidator implements Validator {

//	@Resource(name = "fsCaptchaService")
	protected FSCaptchaService captchaService=FSDigitalCaptchaServiceImpl.getSingleInstance();
	
	@Resource(name="blCustomerService")
	protected FSCustomerService customerService;

	public void validate(FSUpdateMobileForm form, Errors errors,
			HttpSession session) {

		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "mobile",
				"mobile.required");
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "captcha",
				"captcha.required");

		if (!errors.hasErrors()) {
			String captchaMobile=(String) session.getAttribute("captchaMobile");
			String mobile=form.getMobile();
			
			if(captchaMobile!=null && !captchaMobile.equals(mobile)){
				errors.rejectValue("mobile", "mobile.inconsistence");
				return;
			}
			
			boolean isValid = captchaService.validateResponseForID(session.getId(),
					form.getCaptcha(), 0);
			if (!isValid) {
				errors.rejectValue("captcha", "mobile.invalid");
			}
			else if(form.getType()==0){
				//验证手机号是否已绑定
				boolean isBinded=customerService.isMobileBinded(mobile);
				if(isBinded){
					errors.rejectValue("mobile", "mobile.repeat");
				}
			}
			
		}
	}

	@Override
	public boolean supports(Class<?> clazz) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void validate(Object target, Errors errors) {
		// TODO Auto-generated method stub

	}

}
